import { useState, useEffect, useRef } from 'react';
import { Toast } from 'antd-mobile';
import { SyncOutlined } from '@ant-design/icons';

import './style.scss';

function convertBase64UrlToBlob(urlData){
  //去掉url的头，并转换为byte
  const split = urlData.split(',');
  const bytes=window.atob(split[1]);
  //处理异常,将ascii码小于0的转换为大于0
  const ab = new ArrayBuffer(bytes.length);
  const ia = new Uint8Array(ab);
  for (let i = 0; i < bytes.length; i++) {
    ia[i] = bytes.charCodeAt(i);
  }
  return new Blob( [ab] , {type : split[0]});
}

export default function(props) {
  const { onOk, onClose } = props;
  const videoRef = useRef(null);
  const [haveTakenImageUrl, setHaveTakenImageUrl] = useState();
  const [mediaFace, setMediaFace] = useState('environment');
  let stream;

  useEffect(() => {
    handleMediaDevice();
  }, []);

  const onCancel = () => {
    try{
      stream.getTracks().forEach(track => track.stop());
    } catch {  }

    onClose();
  }

  // 打开摄像头
  const handleMediaDevice = async (facingMode = mediaFace) => {
    const { mediaDevices } = window.navigator;
    try {
      stream = await mediaDevices.getUserMedia({
        video: {
          facingMode
        }
      });

      videoRef.current.srcObject = stream;
    } catch {
      (error) => {
        if (error.name === 'PermissionDeniedError') {
          Toast.show('请先允许拍摄权限再尝试');
        } else {
          Toast.show('系统异常');
        }
        onCancel();
      }
    }
  }

  // 点击”翻转摄像头“图标事件
  const handleChangeFace = () => {
    const face = mediaFace === 'user' ? 'environment' : 'user';
    setMediaFace(face);
    handleMediaDevice(face);
  }

  // 点击”拍摄“图标事件
  const hanleTake = () => {
    const canvas = document.createElement('canvas');
    const { offsetWidth: width, offsetHeight: height } = videoRef.current;
    canvas.width = width;
    canvas.height = height;
    canvas.getContext('2d')?.drawImage(videoRef.current, 0, 0, width, height);
    const imgUrl = canvas.toDataURL('image/png');
    setHaveTakenImageUrl(imgUrl);
  }

  // 点击”重拍“事件
  const handleBackToTake = () => {
    setHaveTakenImageUrl('');
    handleMediaDevice();
  }

  const handleSend = () => {
    const blob = convertBase64UrlToBlob(haveTakenImageUrl);
    // const url = URL.createObjectURL(blob);
    // const aElement = document.createElement('a');
    // aElement.setAttribute('href', url);
    // aElement.setAttribute('download', new Date().valueOf() + '.png');
    // URL.revokeObjectURL(url);

    // @ts-ignore
    const file = new File([blob], `${new Date().valueOf()}.jpeg`);
    onOk(file);
  }

  return (<div className="takePhotoPage">
    { !haveTakenImageUrl ?
      <video className="takePhoneVideo" width="100%" ref={videoRef} autoPlay={true} mute="true" playsInline={true}/>
    : <img className="takePhoneImage" src={haveTakenImageUrl} width="100%" />
  }
  { !haveTakenImageUrl ?
      <div className="buttonBar">
        <span onClick={onCancel}>取消</span>
        <div className="takeBtn" onClick={hanleTake}></div>
        <SyncOutlined onClick={handleChangeFace} />
      </div>
      :
      <div className="buttonBar">
        <span onClick={handleBackToTake}>重拍</span>
        <span onClick={handleSend}>使用照片</span>
      </div>
    }
  </div>)
}